# -*-coding: utf-8 -*-

import os
import time
import requests
from subprocess import Popen, PIPE
from celery_app import app
from celery_app import api_url
from celery_app import find_file


# 测试用例目录
case_path_dir = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'autotest', 'app', 'test_case')


@app.task
def test_celery(val):
    time.sleep(5)
    print("test_celery任务结果: %s " % val)
    return "test_celery任务结果: %s " % val


@app.task
def regression_run_test(params):
    """
    回归测试执行入口
    """
    case_file_name = params.get('case_file_name')
    request_id = params.get('request_id')
    path = os.path.join(case_path_dir, 'regression')
    # 获取测试用例路径
    _, file_path_list = find_file(file_name=f'{case_file_name}.py', dir_path=path)
    if not file_path_list:
        print('用例名称错误或不存在')
        return 404

    # 执行测试, 使用nose启动
    start_command = f'python -m nose {file_path_list.pop()}:run -e {request_id}'
    print(start_command)
    # 并发
    Popen(start_command, shell=True, stdout=PIPE, stderr=PIPE)
    return 200


@app.task
def base_run_test(params):
    """
    基础测试执行入口
    """
    case_file_name = params.get('case_file_name')
    request_id = params.get('request_id')
    path = os.path.join(case_path_dir, 'base_case')
    # 获取测试用例路径
    _, file_path_list = find_file(file_name=f'{case_file_name}.py', dir_path=path)
    if not file_path_list:
        print('用例名称错误或不存在')
        return 404

    # 执行测试, 使用nose启动
    start_command = f'python -m nose {file_path_list.pop()}:run -e {request_id}'
    print(start_command)
    # 并发
    Popen(start_command, shell=True, stdout=PIPE, stderr=PIPE)
    return 200


@app.task
def base_schedule_task():
    """
    基础测试定时任务触发器
    """
    resp = requests.get(api_url.execute_base_schedule_task)
    if resp.status_code == 200:
        data = resp.json()
        # if data.get('status') == 'fail':
        print(f'code: {data.get("code")},  message: {data.get("message")}')
    else:
        print(resp.json())
    return 200


if __name__ == '__main__':
    base_schedule_task()
